package com.xuecheng.search.listener;

import com.xuecheng.search.service.SearchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author HuangYuwu
 * @CreateTime 2022/9/15 02:03
 */
@Component
@Slf4j
public class CoursePubListener {
    @Autowired
    private SearchService searchService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "content.pub"),
            exchange = @Exchange(name = "content-exchange", type = ExchangeTypes.TOPIC),
            key = "#.pub"
    ))
    public void listenCoursePub(Long coursePubId){
        try {
            searchService.saveDocument(coursePubId);
        } catch (IOException e) {
            log.error("课程发布id：{}",coursePubId);
        }
    }

    /**
     * 监听课程下架
     * @param courseUnpunId
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "content.unpub"),
            exchange = @Exchange(name = "content-exchange", type = ExchangeTypes.TOPIC),
            key = "#.unpub"
    ))
    public void listenCourseUnpub(Long courseUnpunId){
        try {
            searchService.deleteDocument(courseUnpunId);
        } catch (IOException e) {
            log.error("课程下架id：{}",courseUnpunId);
        }
    }
}
